package com.zqxq.lottery.service.jczq.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.zqxq.common.utils.DispatcherUtils;
import com.zqxq.common.utils.StrUtils;
import com.zqxq.lottery.common.utils.FootBallBetUtils;
import com.zqxq.lottery.entity.po.jczq.JczqMatchLivePO;
import com.zqxq.lottery.entity.po.order.UserOrderBetBopPO;
import com.zqxq.lottery.entity.po.order.UserOrderBetPO;
import com.zqxq.lottery.entity.po.order.UserOrderPO;
import com.zqxq.lottery.entity.vo.jczq.JczqMatchLiveVO;
import com.zqxq.lottery.entity.vo.jczq.JczqMatchVO;
import com.zqxq.lottery.mapper.jczq.JczqMatchLiveMapper;
import com.zqxq.lottery.mapper.order.UserOrderBetBopMapper;
import com.zqxq.lottery.mapper.order.UserOrderBetMapper;
import com.zqxq.lottery.mapper.order.UserOrderMapper;
import com.zqxq.lottery.service.jczq.IJczqMatchResultService;
import com.zqxq.lottery.service.jczq.IJczqMatchService;
import com.zqxq.lottery.util.SelfStringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.*;


@Service
@Slf4j
public class JczqMatchResultServiceImpl extends ServiceImpl<JczqMatchLiveMapper, JczqMatchLivePO> implements IJczqMatchResultService {



    @Override
    public JczqMatchLiveVO get(Long code) {
        Wrapper wrapper = new EntityWrapper();
        wrapper.eq("match_code",code);
        JczqMatchLivePO po = this.selectOne(wrapper);
        JczqMatchLiveVO vo = new JczqMatchLiveVO();
        if(po!=null){
            vo.setId(String.valueOf(po.getId()));
            vo.setInfo(po.getInfo_500());
            vo.setStatus(String.valueOf(po.getStatus()));
            vo.setResult(po.getResult_500());
            vo.setMatchTime(String.valueOf(po.getMatch_time().getTime()));
        }
        return vo;

    }

    @Override
    public Page matchResultList(Map<String, Object> paramMap) {
        Page<Map<String,Object>> page = new Page(DispatcherUtils.parseInt(paramMap.get("pageNo")),DispatcherUtils.parseInt(paramMap.get("pageSize")));
        List<String> cList = baseMapper.matchResultList(page,paramMap);
        List<Map<String,Object>> resultList = new ArrayList();
        for (String code : cList) {
            Map<String,Object> resultMap = new HashMap();
            paramMap.put("code",code);
            List<JczqMatchLiveVO> matchResultList = baseMapper.matchResultListByCode(paramMap);
            if(matchResultList!=null && matchResultList.size()>0){
                resultMap.put("matchField",toWeek(code));
                resultMap.put("matchTime",toDate(code));
                resultMap.put("matchResultList",matchResultList);
                resultList.add(resultMap);
            }
        }
        page.setRecords(resultList);
        return page;
    }


    public static String toDate(String code){
        String date = "";
        if (StrUtils.isNotEmpty(code)){
            date = code.substring(0,4) + "-" + code.substring(4,6) + "-" + code.substring(6,8);
        }
        return date;
    }

    public static String toWeek(String code) {
        String[] weekDays = {"周一", "周二", "周三", "周四", "周五", "周六","周日"};
        String weekDay = "";
        if (StrUtils.isNotEmpty(code)){
            int w = Integer.parseInt(code.substring(8));
            weekDay = weekDays[w-1];
        }
        return weekDay;
    }

    @Autowired
    private UserOrderBetMapper userOrderBetMapper;
    @Autowired
    private UserOrderBetBopMapper userOrderBetBopMapper;
    @Autowired
    private UserOrderMapper userOrderMapper;
    @Autowired
    private IJczqMatchService jczqMatchService;

    @Override
    public Map<String,Object> getBetInfo(String orderId) {
        Map<String,Object> returnMap = new HashMap();
        JSONArray resultList = new JSONArray();
        String expectedBonus = "";
        try {
            List<UserOrderBetPO> OrderBetList = userOrderBetMapper.selectOrderBetList(Long.valueOf(orderId),21L);
            UserOrderPO userOrderPO = userOrderMapper.selectById(orderId);
            List<Double[]> list = new ArrayList();
            for (UserOrderBetPO orderBet : OrderBetList) {
                JSONObject resultMap = new JSONObject();
                JczqMatchVO jczqMatchVO = jczqMatchService.get(orderBet.getPeriod());
                String redNum = orderBet.getRed_num();
                JczqMatchLiveVO jczqMatchResultVO = get(Long.valueOf(orderBet.getPeriod()));
                resultMap.put("matchResult",jczqMatchResultVO.getResult());
                resultMap.put("matchResultInfo",jczqMatchResultVO.getInfo());
                if(!ObjectUtils.isEmpty(jczqMatchVO)){
                    resultMap.put("playType",orderBet.getPlay_type());
                    resultMap.put("matchCode",jczqMatchVO.getCode());
                    resultMap.put("matchField",jczqMatchVO.getMatchField());
                    resultMap.put("hostTeam",jczqMatchVO.getHostTeam());
                    resultMap.put("guestTeam",jczqMatchVO.getGuestTeam());
                    resultMap.put("letNum",jczqMatchVO.getScore());
                    String[] redNums = orderBet.getRed_num().split("\\,");
                    List<Map<String,Object>> betList = new ArrayList();
                    Map<String,String> oddsMap = new HashMap();
                    for (int i=0;i<redNums.length;i++) {
                        Map<String,Object> matchMap = new HashMap();
                        matchMap.put("betNum",redNums[i]);
                        matchMap.put("odds",orderBet.getBlue_num().split("\\,")[i]);
                        betList.add(matchMap);
                        oddsMap.put(redNums[i],orderBet.getBlue_num().split("\\,")[i]);
                    }
                    resultMap.put("betList",betList);
                    Double[] m1 = FootBallBetUtils.getMinMaxOdds(redNum,oddsMap);
                    list.add(m1);
                }

                resultList.add(resultMap);
            }
            Double minBonus = FootBallBetUtils.betMinVal(userOrderPO.getBet_bunch().split(","), list);
            Double maxBonus = FootBallBetUtils.betMaxVal(userOrderPO.getBet_bunch().split(","), list);
            BigDecimal min = new BigDecimal(minBonus).multiply(new BigDecimal(userOrderPO.getBet_times())).setScale(2,BigDecimal.ROUND_HALF_UP);
            BigDecimal max = new BigDecimal(maxBonus).multiply(new BigDecimal(userOrderPO.getBet_times())).setScale(2,BigDecimal.ROUND_HALF_UP);
            if(userOrderPO.getIs_bonus_optimize()!=null && userOrderPO.getIs_bonus_optimize()==0){
                Wrapper wrapper = new EntityWrapper();
                wrapper.eq("order_id",orderId);
                List<UserOrderBetBopPO> userOrderBetBopPOS = userOrderBetBopMapper.selectList(wrapper);
                SelfStringUtils.sortByAttribute(userOrderBetBopPOS);
                BigDecimal totalExpectBonus = BigDecimal.ZERO;
                for(UserOrderBetBopPO userOrderBetBopPO : userOrderBetBopPOS){
                    totalExpectBonus = totalExpectBonus.add(userOrderBetBopPO.getExpect_bonus());
                }
                expectedBonus = userOrderBetBopPOS.get(0).getExpect_bonus() + "~" + totalExpectBonus;
            }else {
                expectedBonus = String.valueOf(min) + "~" + String.valueOf(max);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        returnMap.put("expectedBonus",expectedBonus);
        returnMap.put("resultList",resultList);
        return returnMap;
    }

    public JczqMatchLiveVO saveMatchResult(JczqMatchLiveVO vo){
        String id = vo.getId();
        if(!StringUtils.isEmpty(id)){
            JczqMatchLivePO jczqMatchLivePO = baseMapper.selectById(id);
            jczqMatchLivePO.setMatch_code(vo.getMatchCode());
            jczqMatchLivePO.setMatch_field(vo.getMatchField());
            jczqMatchLivePO.setLeague(vo.getLeague());
            jczqMatchLivePO.setLeague_id(DispatcherUtils.parseLong(vo.getLeagueId()));
            jczqMatchLivePO.setHost_team(vo.getHostTeam());
            jczqMatchLivePO.setGuest_team(vo.getGuestTeam());
            jczqMatchLivePO.setResult(vo.getResult());
            jczqMatchLivePO.setInfo(vo.getInfo());
            jczqMatchLivePO.setResult_500(vo.getResult500());
            jczqMatchLivePO.setInfo_500(vo.getInfo500());
            jczqMatchLivePO.setHalf_score(vo.getHalfScore());
            jczqMatchLivePO.setStatus(DispatcherUtils.parseInteger(vo.getStatus()));
            jczqMatchLivePO.setType(1);
            jczqMatchLivePO.setScore(vo.getScore());
            jczqMatchLivePO.setGame_state(vo.getGameState());
            jczqMatchLivePO.setGoal_line(vo.getGoalLine());
            baseMapper.updateById(jczqMatchLivePO);
        }

        return vo;
    }
}
